package com.jaydenxiao.common.base;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.jaydenxiao.common.BuildConfig;
import com.jaydenxiao.common.R;
import com.jaydenxiao.common.baseapp.AppManager;
import com.jaydenxiao.common.baseapp.BaseApplication;
import com.jaydenxiao.common.commonutils.TUtil;
import com.jaydenxiao.common.commonutils.ToastUitl;
import com.jaydenxiao.common.commonwidget.LoadingDialog;
import com.jaydenxiao.common.commonwidget.StatusBarCompat;
import com.jaydenxiao.common.fragmentUtils.FragmentTagConstant;
import com.jkb.fragment.rigger.annotation.Puppet;
import com.jkb.fragment.rigger.rigger.Rigger;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Stack;

import butterknife.ButterKnife;
import butterknife.Unbinder;

@Puppet(stickyStack = true)
public abstract class BaseActivity<V extends BaseView, T extends BasePresenter<V>> extends RxAppCompatActivity implements BaseView {
    public T mPresenter;
    protected Activity mActivity;
    public Context mContext;
    private boolean isConfigChange = false;

    protected TextView toolbar_header;
    protected Toolbar toolbar;
    public boolean isNeedConfirmAppExit = false;

    //ButterKnife
    private Unbinder mUnbinder;
    public long mExitTime;

    //状态栏
    private ImmersionBar immersionBar;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isConfigChange = false;
        doBeforeSetcontentView();
        //setContentView(getLayoutId());
        setContentView(R.layout.base_layout);
        FrameLayout frameLayout = findViewById(R.id.base_container);
        if (getLayoutId() != 0) {
            View view = View.inflate(this, getLayoutId(), null);
            frameLayout.addView(view, 0);
        }
        mUnbinder = ButterKnife.bind(this);
        mActivity = this;
        mContext = getBaseContext();
        //初始化P和M
        mPresenter = TUtil.getT(this, 1);
        if (mPresenter != null) {
            mPresenter.mContext = this;
            mPresenter.attachView((V) this);
        }
        handIntent();
        initView();
        initImmersionBar();
    }


    /**
     * Puppet,源码中可以用这个设置id
     *
     * @return
     */
    public int getContainerViewId() {
        return R.id.base_container;

    }

    /**
     * 沉浸式状态栏ImmersionBar
     */
    private void initImmersionBar() {
        if (isImmersionBarEnabled()) {
            immersionBar = ImmersionBar.with(this);
            // 所有子类都将继承这些相同的属性,请在设置界面之后设置
            immersionBar.fitsSystemWindows(true).statusBarColor(R.color.white).statusBarDarkFont(true, 0.2f).init();  //必须调用方可沉浸式  //状态栏字体是深色
        }
    }


    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return true;
    }

    /**
     * 设置layout前配置
     **/
    private void doBeforeSetcontentView() {
        // 把actvity放到application栈中管理
        AppManager.getAppManager().addActivity(this);
        // 无标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 设置竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    }

    /*********************子类实现*****************************/
    //获取布局文件
    public abstract int getLayoutId();

    public void handIntent() {
    }

    //初始化view
    public abstract void initView();

    /**
     * token,重新登录,当前页面需要刷新的刷新数据
     */
    public abstract void tokenInvalidRefresh();


    //初始化toolbar
    protected void initToolbar(int title, boolean showNavigationIcon, boolean menuItemClick,
                               OnMenuClickListener onMenuClickListener) {
        initToolbar(this.getResources().getString(title), showNavigationIcon, menuItemClick, onMenuClickListener);
    }

    //初始化toolbar
    @SuppressWarnings("ConstantConditions")
    protected void initToolbar(String title, boolean showNavigationIcon,
                               boolean menuItemClick, final OnMenuClickListener onMenuClickListener) {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar_header = (TextView) findViewById(R.id.toolbar_title_tv);
        toolbar_header.setText(title);

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        if (showNavigationIcon) {
            toolbar.setNavigationIcon(R.drawable.back);
            // Menu item click 的監聽事件一樣要設定在 setSupportActionBar 才有作用
            // toolbar.setOnMenuItemClickListener(onMenuItemClick);
            //设置toolbar右侧的点击事件
            toolbar.setNavigationOnClickListener(v -> {
                if (listener != null) listener.onNavigationClick();
                finish();
            });
        }
        if (menuItemClick) {
            toolbar.setOnMenuItemClickListener(item -> {
                onMenuClickListener.onItemClick(item);
                return false;
            });
        }
    }

    //点击事件的回调
    public interface OnMenuClickListener {
        void onItemClick(MenuItem item);
    }

    //点击返回需要处理的东西
    OnNavigationOnClickListener listener;

    public interface OnNavigationOnClickListener {
        void onNavigationClick();
    }

    public void setOnNavigationOnClickListener(OnNavigationOnClickListener listener) {
        this.listener = listener;
    }

    /**
     * 着色状态栏（4.4以上系统有效）
     **/
    protected void SetStatusBarColor() {
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_status));
    }

    /**
     * 着色状态栏（4.4以上系统有效）
     **/
    protected void SetStatusBarColor(int color) {
        StatusBarCompat.setStatusBarColor(this, color);
    }

    /**
     * 沉浸状态栏（4.4以上系统有效）
     **/
    protected void SetTranslanteBar() {
        StatusBarCompat.translucentStatusBar(this);
    }


    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) intent.putExtras(bundle);
        startActivityForResult(intent, requestCode);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) intent.putExtras(bundle);
        startActivity(intent);
    }


    public void setNeedConfirmAppExit(boolean needConfirmAppExit) {
        isNeedConfirmAppExit = needConfirmAppExit;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.<T>bindToLifecycle();

    }


    /**
     * token失效
     */
    @Override
    public void tokenInvalid() {
        String fragmentCls = "com.radioapp.liaoliaobao.module.user.login.LoginFragment";
        try {
            Fragment fragment = (Fragment) Class.forName(fragmentCls).newInstance();
            //跳登录
            if (fragment != null) {
                Stack<String> strings = Rigger.getRigger(mActivity).getFragmentStack();
                for (int i = 0; i < strings.size(); i++) {
                    if (strings.get(i).contains("LoginFragment")) {
                        strings.remove(i);
                    }
                }
             Fragment loginFragment=   Rigger.getRigger(mActivity).findFragmentByTag(fragmentCls);
                if(loginFragment!=null){
                    Rigger.getRigger(mActivity).showFragment(fragmentCls);
                }else{
                    Rigger.getRigger(mActivity).startFragment(fragment);
                }



            } else {
                //如果找不到fragment就跳登录页面
                Intent intent = new Intent();
                String cls = "com.radioapp.liaoliaobao.module.user.login.LoginActivity";
                intent.setComponent(new ComponentName(mActivity, cls));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mActivity.startActivity(intent);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (java.lang.InstantiationException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (isNeedConfirmAppExit) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
                    && event.getAction() == KeyEvent.ACTION_DOWN
                    && event.getRepeatCount() == 0) {
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                    mExitTime = System.currentTimeMillis();
                    return false;
                } else {
                    AppManager.getAppManager().AppExit(this, true);
                    return true;
                }
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //debug版本不统计crash

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        isConfigChange = true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!isConfigChange) AppManager.getAppManager().finishActivity(this);
        if (mUnbinder != null) mUnbinder.unbind();
        if (mPresenter != null)
            mPresenter.detachView();

        if (immersionBar != null) {
            //必须调用该方法，防止内存泄漏，不调用该方法，如果界面bar发生改变，在不关闭app的情况下，退出此界面再进入将记忆最后一次bar改变的状态
            immersionBar.destroy();
        }
    }



      @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(activityResultByFragment!= null){
            activityResultByFragment.onActivityResultByFragment(requestCode,resultCode,data);
        }
    }




    ActivityResultByFragment activityResultByFragment;

    public void setActivityResultByFragment(ActivityResultByFragment activityResultByFragment) {
        this.activityResultByFragment = activityResultByFragment;
    }

    /**
     * 调用第三方的东西需要fragment的类
     */
   public  interface ActivityResultByFragment{
       void onActivityResultByFragment(int requestCode, int resultCode, Intent data);
    }

}
